package com.gxa.educate.portal.tablet.earlyeducation.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gxa.educate.core.common.JsonResult;
import com.gxa.educate.portal.tablet.earlyeducation.config.AlipayConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class AlipayController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String INFORMATION = "information:";
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    JsonResult jsonResult = new JsonResult();
    private BoundHashOperations<String, Object, Object> hashOperations = null;

    @ApiOperation(value = "用户充值")
    @RequestMapping("/alipay")
    public void alipay(@ApiIgnore HttpServletResponse httpResponse, @ApiIgnore HttpServletRequest request, HttpSession session, @RequestParam("money") String money
            , @RequestParam("phone") String phone, @RequestParam("day") String day) throws IOException {
        hashOperations = redisTemplate.boundHashOps(INFORMATION + phone);
        hashOperations.put("day", day);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String WIDsubject = "xkhnlhml";
        String WIDbody = "充值界面";
//        Map<String, Object> objectMap = new HashMap<String, Object>();
//        objectMap.put("price", request.getParameter("productTotalPrice"));
//        session.setAttribute("payInfo", objectMap);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = UUID.randomUUID().toString().replaceAll("-", "");
//        		new String(request.getParameter("ids").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String many = new String(money.getBytes("ISO-8859-1"), "UTF-8");
        hashOperations.put("money", many);
        String phones = new String(phone.getBytes("ISO-8859-1"), "UTF-8");
        hashOperations.put("phone", phone);
        //订单名称，必填
        String subject = new String(WIDsubject.getBytes("ISO-8859-1"), "UTF-8");
        //商品描述，可空
        String body = new String(WIDbody.getBytes("ISO-8859-1"), "UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + many + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = "";
        try {
            // 调用SDK生成表单
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset=" + AlipayConfig.charset);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(result);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    /**
     * 注意异步返回结果通知是以post请求形式返回的
     *
     * @param request
     * @return
     */
    @PostMapping("notifyUrl")
    public String notify_url(HttpSession session, HttpServletRequest request) throws Exception {
        hashOperations = redisTemplate.boundHashOps(INFORMATION + request.getParameter("phone"));
        String flag = "1";
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        String out_trade_no = paramsMap.get("out_trade_no");
        String tradeStatus = paramsMap.get("trade_status");
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            //无论同步异步都要验证签名
            if (signVerified) {
                if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
                    Map map = new HashMap();
                    String day = hashOperations.get("day").toString();
                    calendar.add(Calendar.DATE, Integer.parseInt(day));
                    String phone = hashOperations.get("phone").toString();
                    String many = hashOperations.get("money").toString();
                    // User user = userService.selectMany(phone);
                    // Integer total = Integer.parseInt(many) + user.getMoney();
//                    map.put("money", total);
//                    map.put("phone", phone);
//                    map.put("time", calendar.getTime());
//                    userService.updateManyAndTime(map);
//                    Map map1 = userService.selectDay(phone);
//                    String day1 = (String) map1.get("day");
//                    flag = day1;
                }
            } else {
                //签名验证失败不处理业务逻辑
                flag = "0";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }

    //注意同步返回结果是以get请求形式返回的
    @GetMapping("returnUrl")
    public String return_url(HttpServletRequest request) throws Exception {
        String flag = "1";
        JsonResult jsonResult = new JsonResult();
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            if (signVerified) {
                HttpSession session = request.getSession();
                String phone = (String) session.getAttribute("phone");
                String many = (String) session.getAttribute("many");
                String day = (String) session.getAttribute("day");
//                Map map1 = userService.selectOverDay(phone);
//                Map map2 = new HashMap();
//                List<User> users = userService.selectIdByPhone(phone);
//                map2.put("uid", users.get(0).getId());
//                map2.put("money", many);
//                userService.insertMoney(map2);
                //获取数据库会员过期时间
                String date = new SimpleDateFormat("yyyy-MM-dd").format("time");
                System.out.println("over" + date);
                //获取当前系统时间
                String date1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                System.out.println("当前" + date1);
                Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(date);
                Date parse1 = new SimpleDateFormat("yyyy-MM-dd").parse(date1);
                Map map = new HashMap();
                //将两个时间相减转换为int类型
                Long time = (parse.getTime() - parse1.getTime());
                System.out.println("相减" + time);
                if (time > 0) {
                    calendar.add(Calendar.DATE, (Integer.parseInt(day) + ((int) (time / (1000 * 3600 * 24)))));
                } else {
                    calendar.add(Calendar.DATE, Integer.parseInt(day));
                }

//                User user = userService.selectMany(phone);
//
//                Integer total = Integer.parseInt(many) + user.getMoney();
//                map.put("money", total);
//                map.put("phone", phone);
//                map.put("time", calendar.getTime());
//                userService.updateManyAndTime(map);
//                jsonResult.setData(userService.selectDay(phone));
            } else {
                //跳转支付失败界面
                jsonResult.setData("0");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }


    //将请求中的参数转换为Map
    public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        Iterator var3 = entrySet.iterator();

        while (true) {
            while (var3.hasNext()) {
                Map.Entry<String, String[]> entry = (Map.Entry) var3.next();
                String name = (String) entry.getKey();
                String[] values = (String[]) entry.getValue();
                int valLen = values.length;
                if (valLen == 1) {
                    retMap.put(name, values[0]);
                } else if (valLen <= 1) {
                    retMap.put(name, "");
                } else {
                    StringBuilder sb = new StringBuilder();
                    String[] var9 = values;
                    int var10 = values.length;

                    for (int var11 = 0; var11 < var10; ++var11) {
                        String val = var9[var11];
                        sb.append(",").append(val);
                    }

                    retMap.put(name, sb.toString().substring(1));
                }
            }

            return retMap;
        }
    }

    //将字符串转换为UTF-8编码以防出现乱码错误
    public static String getUTF8XMLString(String xml) {
        StringBuffer sb = new StringBuffer();
        sb.append(xml);
        String xmString = "";
        String xmlUTF8 = "";
        try {
            xmString = new String(sb.toString().getBytes("UTF-8"));
            xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return xmlUTF8;
    }

    //退款
    @RequestMapping("/payReturn")
    public void payReturn() throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", "2022071322001454010501876395");
        bizContent.put("refund_amount", 100);
        bizContent.put("out_request_no", "");

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
}
